﻿using System;
using Oblivion.Clients;
using Oblivion.Substructure;

namespace Oblivion.Networking
{
    public static class GameWorker
    {
        //I removed the documentation for this class because it distracted me! x.x

        public static void Connect(Passport passport)
        {
            var client = new GameClient(passport);
            passport.Client = client;

            Kernel.ConnectedClients.Add(client);
        }

        public static void Receive(Passport passport, byte[] buffer)
        {
            try
            {
                var client = passport.Client as GameClient;
                if (client != null)
                {
                    if (client.IsEncryptioned)
                        buffer = client.Encryption.Decrypt(buffer);
                    if (buffer.Length > 0)
                        PacketProcessor.ProcessPacket(buffer, client);
                }

                #region stuff no worky

                // Doesn't work with minecraft! Needs to be optimzed!
                // Split up the buffer into packets:
                // While the reported packet length if less than the buffer, split packets.
//                while (buffer.Length >= 4 && BitConverter.ToUInt16(buffer, 0) <= buffer.Length)
//                {
//                    // Get the length and error check it.
//                    // Does the length even make sense?!
//#warning Biest towards CO?
//                    int expectedLength = BitConverter.ToUInt16(buffer, 0);
//                    if (expectedLength > 1000)
//                        return;

//                    // Create a new array for the packet and copy:
//                    byte[] packet = new byte[expectedLength];
//                    Array.Copy(buffer, packet, expectedLength);

//                    // Remove the packet from the array:
//                    byte[] newBuffer = new byte[buffer.Length - expectedLength];
//                    if (newBuffer.Length > 0)
//                        Array.Copy(buffer, expectedLength, newBuffer, 0, newBuffer.Length);
//                    buffer = newBuffer;

//                    // Handle the new packet:
//                    //PacketHandler.Handle(client, packet);
//                }

                #endregion
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                Console.WriteLine("\n\n" + e.Message);
            }
        }

        public static void Disconnect(Passport passport)
        {
            var client = passport.Client as GameClient;
            if (client != null)
            {
                client.DisconnectSocket();
            }
            passport = null;
        }
    }
}